package com.superquan.selfstudybootmybatis.controller;

import com.superquan.selfstudybootmybatis.entity.common.ResultBean;
import com.superquan.selfstudybootmybatis.utils.pdfanalysis.PdfUtil;
import net.sf.json.JSONObject;
import org.apache.catalina.connector.Request;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @author zwq
 * @description pdf相关处理控制层
 * @date 2022/6/24
 */
@RestController
public class PdfController {

    @PostMapping(value = "/pdf/downloadFile")
    public String  downloadFile(HttpServletRequest request,HttpServletResponse response){
        String json = request.getParameter("json");
        try {
            json = java.net.URLDecoder.decode(json,"UTF-8");  //解码
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.fromObject(json);
        Map<String, Object> mapJson = JSONObject.fromObject(jsonObject);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setCharacterEncoding("UTF-8");
        // 定义输出类型
        response.setContentType("application/PDF;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + "assessment.pdf");
        try {
            ServletOutputStream out = response.getOutputStream();
            PdfUtil pdf = new PdfUtil();
            pdf.fillTemplate(mapJson ,out,"C:\\Users\\admin\\Desktop\\contract.pdf");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    @PostMapping(value = "/pdf/fillPdfTemplate")
    public ResultBean fillPdfTemplate(HttpServletRequest request){
        ResultBean resultBean=new ResultBean();
        String paramJson = request.getParameter("param");
        try {
            paramJson = java.net.URLDecoder.decode(paramJson,"UTF-8");  //解码
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            resultBean.setCode(10000);
            resultBean.setMessage("赋值异常！");
            return resultBean;
        }
        JSONObject jsonObject = JSONObject.fromObject(paramJson);
        Map<String, Object> mapJson = JSONObject.fromObject(jsonObject);
        PdfUtil.fillPdfTemplate(mapJson);
        resultBean.setCode(0);
        resultBean.setMessage("赋值成功！");
        return resultBean;
    }
}
